package com.tencent.cloud.iov.kernel.service.interceptor;

import android.util.Pair;

import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.kernel.util.ExceptionUtils;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * @author vinsonhuang
 * @date 2018/5/16
 */
public class ExceptionTransformer<T> implements ObservableTransformer<BaseResponse<T>,
        BaseResponse<T>> {

    @Override
    public ObservableSource<BaseResponse<T>> apply(Observable<BaseResponse<T>> upstream) {
        return upstream
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends
                        BaseResponse<T>>>() {
                    @Override
                    public ObservableSource<? extends BaseResponse<T>> apply(Throwable throwable)
                            throws Exception {
                        // 处理本地异常消息
                        Pair<Integer, String> pair = ExceptionUtils.handleThrowable(throwable);
                        return Observable.just(new BaseResponse<T>(pair.first, pair.second));
                    }
                });
    }
}
